<?php

namespace App\Http\Middleware;

use Closure;
use Intervention\Image\Facades\Image;

class ImageResizeMiddleware {

    public function handle($request, Closure $next)
    {
        $path = $request->path();
        $uri = $request->getRequestUri();

        $path = str_replace('image', 'images', $path);
        $file = public_path().'/'.$path;

        $hash = substr(md5($uri), 0 , 2);


        if (preg_match("/(^.*).(png|jpg|jpeg|gif)\?(\d+)x(\d+)/", $uri, $match)) {
            $toFile = public_path('images').'/'.$hash.'/'.md5($uri).'.'.$match[2];

            if(file_exists($toFile))
            {
                $im = Image::make($toFile);
                return $im->response(strtolower($match[2]), 90, 200);
            }
            if (file_exists($file)) {
                $width = intval($match[3]);
                $height = intval($match[4]);


                if ($width && $height) {
                    $im = Image::make($file)->fit($width ? $width : null, $height ? $height : null, function($constraint) {
                        $constraint->upsize();
                    });
                } else {
                    $im = Image::make($file)->resize($width ? $width : null, $height ? $height : null, function($constraint) {
                        $constraint->aspectRatio();
                        $constraint->upsize();
                    });
                }


                try {
                    $pathInfo = pathinfo($toFile);
                    if(!is_dir($pathInfo['dirname']))
                    {
                        mkdir($pathInfo['dirname']);
                    }
                    $im->save($toFile, 90);
                } catch (\Exception $e) {
                    // I don't care.
                }

                return $im->response(strtolower($match[2]));
            }
        }

        return $next($request);
    }
}